package chain_apply

import (
	"chain_bridge_service/configs"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *ChainApply {
	return new(ChainApply)
}

// 根据userId和from查询 总数
func (c *ChainApply) Count(client *mongo.Client) (int64, error) {
	cfg := configs.Get().Mongodb
	applyClient := client.Database(cfg.Config.Name).Collection("chain_apply")
	filter := bson.M{"userId": c.UserId}
	if c.From != "" {
		filter["from"] = c.From
	}

	if c.TxHash != "" {
		filter["txHash"] = c.TxHash
	}
	count, err := applyClient.CountDocuments(context.TODO(), filter)
	if err != nil {
		return 0, err
	}
	return count, nil
}

func (c *ChainApply) List(client *mongo.Client, pageIndex uint, pageSize uint) ([]ChainApply, error) {

	cfg := configs.Get().Mongodb
	var chainApplyList []ChainApply
	applyClient := client.Database(cfg.Config.Name).Collection("chain_apply")
	// 根据userId和from查询 并且根据时间倒序排 并p分页
	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"timeStamp", -1}})
	findOptions.SetSkip(int64((pageIndex - 1) * pageSize))
	findOptions.SetLimit(int64(pageSize))

	filter := bson.M{"userId": c.UserId}
	if c.TxHash != "" {
		filter["txHash"] = c.TxHash
	}

	if c.From != "" {
		filter["from"] = c.From
	}
	find, err := applyClient.Find(context.TODO(), filter, findOptions)
	if err != nil {
		return nil, err
	}
	err = find.All(context.TODO(), &chainApplyList)
	if err != nil {
		return nil, err
	}

	return chainApplyList, nil
}

func (c *ChainApply) Create(client *mongo.Client) error {
	cfg := configs.Get().Mongodb
	applyClient := client.Database(cfg.Config.Name).Collection("chain_apply")
	_, err := applyClient.InsertOne(context.TODO(), c)
	return err
}
